package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.Chart;
import com.example.domain.Result;
import com.example.dao.BookDao;
import com.example.domain.Book;
import com.example.util.POIUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {

    @Autowired
    private BookDao bookDao;

    @Override
    public boolean saveBook(Book book) {
        return bookDao.insert(book) > 0;
    }

    @Override
    public boolean modify(Book book) {
        return bookDao.updateById(book) > 0;
    }

    @Override
    public boolean delete(Integer id) {
        return bookDao.deleteById(id) > 0;
    }

    @Override
    public IPage<Book> getPage(int currentPage, int pageSize) {
        IPage page = new Page(currentPage,pageSize);
        bookDao.selectPage(page,null);
        return page;
    }

    @Override
    public IPage<Book> getPage(int currentPage, int pageSize, Book book) {
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<Book>();
        lqw.like(Strings.isNotEmpty(book.getType()),Book::getType,book.getType());
        lqw.like(Strings.isNotEmpty(book.getName()),Book::getName,book.getName());
        lqw.like(Strings.isNotEmpty(book.getAuthor()),Book::getAuthor,book.getAuthor());
        IPage page = new Page(currentPage,pageSize);
        bookDao.selectPage(page,lqw);
        return page;
    }
    public Result uploadfile(MultipartFile file) throws IOException {
        if(file == null){
           return new Result(false,"上传失败，文件为空");
        }else{
            List<String[]> list = POIUtil.readExcel(file);
            for (int i = 0; i <list.size(); i++) {
                String[] s = list.get(i);
                Book book = new Book();
                book.setType(s[0]);
                book.setName(s[1]);
                book.setAuthor(s[2]);
                book.setPublishingHouse(s[3]);
                book.setBuyNumber(Integer.parseInt(s[4]));
                saveBook(book);
            }
            return new Result(true,"上传成功");
        }
    }
    public Result getChart(){
        //Chart list = bookDao.getChart();
        List<Book> list = bookDao.getChart();
        if(list == null){
            return new Result(false);
        }
        return new Result(true,list);
    }
}
